import React, {Component} from "react";
import {Form, Input, Icon, Button} from 'antd'
import {login} from "../../api/admin";
import {setToken, setUserInfo} from "../../utils/auth";

const FormRules = {
  username: [{required: true, message: 'Please input your username!'}],
  password: [{required: true, message: 'Please input your username!'}]
};

@Form.create()
class Login extends Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (err) {

      } else {
        login({
          login_name: values.username.trim(),
          password: values.password
        }).then(res => {
          const {data} = res;
          setToken(data.token);
          setUserInfo(data);
        }).catch(error => {

        })
      }

    });
  };

  render() {
    // console.log(this.props.form);
    const {getFieldDecorator} = this.props.form;
    return (
        <div>
          <h1>login</h1>
          <Form onSubmit={this.handleSubmit} className="login-form">
            <Form.Item label="用户名">
              {getFieldDecorator('username', {
                rules: FormRules.username
              })(<Input prefix={<Icon type="user" style={{color: 'rgba(0,0,0,.25)'}}/>}
                        placeholder="Username"/>)}
            </Form.Item>
            <Form.Item label="密码">
              {getFieldDecorator('password', {
                rules: FormRules.password
              })(<Input prefix={<Icon type="lock" style={{color: 'rgba(0,0,0,.25)'}}/>}
                        type="password"
                        placeholder="Password"/>)}
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" className="login-form-button">
                Log in
              </Button>
            </Form.Item>
          </Form>
        </div>

    )
  }
}

export default Login